<template>
	<u-keyboard mode="number" :dot-enabled="false" :random="true" :cancel-btn="false" :confirm-btn="false"
		:safe-area-inset-bottom="true" :modelValue="showKeyBoard" :show-tips="showTips" :tooltip="tooltip"
		confirmText='完成' closeOnClickOverlay @change="handleChange" @backspace="handleBack">
		<view class="keyboard_bg pdt-52 pdb-52">
			<view class="title flex-jc pdb-52 fs32">输入验证码确认借款</view>
			<u-message-input :focus="true" :maxlength="maxlength" :disabled-keyboard="true"
				v-model="codeValue"></u-message-input>
			<view class=" fs24 pdl-64 pdr-64 pdt-44" :class="countdownTime>0 ?'code_text': 'code_default'" v-if="isTips"
				@click="handleCode">
				{{ countdownTime > 0 ? `重新获取${countdownTime}s` : '获取验证码' }}
			</view>
		</view>
	</u-keyboard>
</template>

<script lang="ts" setup>
	import { ref, watch,onUnmounted } from 'vue';

	const props = defineProps({
		showKeyBoard: {
			type: Boolean,
			default: false
		},
	})

	const showTips = ref<boolean>(false)
	const tooltip = ref<boolean>(false)
	const maxlength = ref<string>("6")
	const countdownTime = ref<number>(60)
	const timer = ref<NodeJS.Timeout | null>(null);
	const isTips = ref<boolean>(false)
	const codeValue = ref<string>("")

	const handleChange = (v : number) => {
		if (codeValue.value.length >= Number(maxlength.value) - 1) {
			isTips.value = true
			startTimer()
			uni.redirectTo({
				url:'/pages/audit/index'
			})
		}
		if (codeValue.value.length === 6) {
			return
		}
		codeValue.value += String(v)
	}

	const handleBack = () => {
		if (codeValue.value.length > 0) {
			codeValue.value = codeValue.value.slice(0, -1);
		}
	};

	const stopTimer = () => {
		if (timer.value) {
			clearInterval(timer.value)
			timer.value = null
		}
	}

	const startTimer = () => {
		stopTimer();
		countdownTime.value = 60;
		timer.value = setInterval(() => {
			countdownTime.value--;
			if (countdownTime.value <= 0) {
				stopTimer();
			}
		}, 1000);
	};

	const handleCode = async () => {
		if (countdownTime.value > 0 && timer.value) return
		countdownTime.value = 60
		startTimer()
		// let res = await getCode(form.value.phonenumber)
		// if(res){
		// 	
		// }
	}
	
	onUnmounted(() => {
		stopTimer()
	})
</script>

<style lang="scss" scoped>
	@import '@/style/style.scss';

	.keyboard_bg {
		background: #F8F9FD;

		.title {
			color: #2D2E33;
			font-weight: bold;
			font-family: PingFang SC;
		}

		.code_text {
			display: flex;
			justify-content: flex-end;
			font-family: PingFang SC;
			font-weight: 500;
			color: #999999;
		}

		.code_default {
			@extend .code_text;
			color: #3C51F2;
		}
	}
</style>